package com.deimos.sps;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vast.ows.OWSException;

import org.vast.ows.sps.SPSUtils;
import org.vast.ows.swe.DescribeSensorRequest;

import com.deimos.dataBase.Sensor;

public class DescribeSensorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * So far this Servlet just is implemented in order to show what is expected
     * to return the GetCapabilities service. As soon is define the schema of
     * the Xml GetCapabilities response it will be updated
     * 
     * @param req
     * @param res
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	Date start = new Date();
	String queryString = req.getQueryString();

	try {
	    /*
	     * Due to a bug in the library. The GetCapabilities call has changed
	     * in OWS Common 1.1 and the changes are not yet reflected in the
	     * library. If you want the right behaviour, you can however simply
	     * not use the library for this operation since it is very simple to
	     * parse.
	     */
	    if ((queryString.toLowerCase().contains("service=sps") && queryString.toLowerCase().contains("request=describesensor") && queryString.toLowerCase().contains("format=SensorMLv1.0"))) {
		this.GetCapabilities(req, res);
	    } else {
		PrintWriter out = res.getWriter();
		out.println("Http parameters not correct");
		out.close();

		throw new java.io.IOException("Http parameters not correct " + this.getClass().getName());
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	System.out.println("Execution time: " + ((new Date()).getTime() - start.getTime()));
    }

    private void GetCapabilities(HttpServletRequest req, HttpServletResponse res) throws OWSException {
	PrintWriter out = null;
	SPSUtils utils = new SPSUtils();
	try {
	    DescribeSensorRequest request = (DescribeSensorRequest) utils.readURLQuery(req.getQueryString(), "SPS", "2.0");

	    if (request.getService().equals("SPS")) {
		out = res.getWriter();
		out.println(Sensor.readDescription(request.getProcedureID()));
	    }
	    out.close();

	} catch (Exception e) {
	    try {
		out = new PrintWriter(res.getWriter());
		out.println("Sensor not found");
	    } catch (Exception ex) {
	    }
	    e.printStackTrace();
	}
    }
}
